﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormsApplication9
{
    public abstract class iDS
    {
        protected virtual string fileName { get; set; }
        public virtual void Clear() { throw new ArgumentNullException("IDataStorage: Not valid Data, try IDS_Classed"); }
        public virtual void Create(Person _newPerson) { throw new ArgumentNullException("IDataStorage: Not valid Data, try IDS_Classed"); }
        public virtual List<Person> Read() { throw new ArgumentNullException("IDataStorage: Not valid Data, try IDS_Classed"); }
        public virtual void Delete(int id) { throw new ArgumentNullException("IDataStorage: Not valid Data, try IDS_Classed"); }
        public virtual void Update(int id, Person _PersonDataToUpdate) { throw new ArgumentNullException("IDataStorage: Not valid Data, try IDS_Classed"); }
        public virtual iDS IsReady(string filename) { return null; }
        public virtual string GetFilter() { return ""; }
        public iDS next { get; set; }


    } //---- class iDS

    public class DS_Net_Client : iDS
    {
        private List<Person> SendToServer(string request)
        {
            List<Person> list = new List<Person>();
            try
            {
                string host = System.Net.Dns.GetHostName();
                int port = 8000;
                WebClient client = new WebClient();
                byte[] msg = Encoding.UTF8.GetBytes(request + "\n");

                //Send message
                byte[] buf  = client.UploadData("http://" + host + ":" + port + "/"/* + request*/, msg);
                //decoding from bytes array to string
                string answer = Encoding.UTF8.GetString(buf);
                client.Dispose();
                
/*
//send
HttpWebRequest web_request = (HttpWebRequest)WebRequest.Create("http://localhost:8000/" + request);

//recieve
HttpWebResponse response = (HttpWebResponse)web_request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());

string answer = sr.ReadToEnd();
sr.Close();
*/

                //analyse answer from Net_Server
                if (answer == "fail")
                {
                    throw new SystemException("DS_Net_Client.Create(Person _newPerson) failed");
                }

                // else
                // Parsing the answer
                if (answer != "success")
                {
                    string[] data = answer.Split('\n');
                    for (int i = 0; i < data.Length - 1; i++)
                    {
                        Person a = new Person();
                        a.CreateFromLineCsv(data[i]);
                        list.Add(a);
                    }
                }
            }
            catch (Exception t)
            {
                MessageBox.Show(t.Message, "exeption");
            }
            return list;
        }
        //--------------------------------------------------------
        public override void Clear()
        {
            string request = "CLEAR;";
            SendToServer(request);
        }

        //--------------------------------------------------------
        public override void Create(Person _newPerson)
        {
            string request = "CREATE;" + _newPerson.ReturnLineToCsv();
            SendToServer(request);
        }

        //--------------------------------------------------------
        public override List<Person> Read()
        {
            string request = "READ;";
            return SendToServer(request);
        }

        //--------------------------------------------------------
        public override void Delete(int id)
        {
            string request = "DELETE;" + Convert.ToString(id);
            SendToServer(request);
        }

        //--------------------------------------------------------
        public override void Update(int id, Person _newPerson)
        {
            string request = "UPDATE;" + Convert.ToString(id) + ";" + _newPerson.ReturnLineToCsv();
            SendToServer(request);
        }

        //--------------------------------------------------------
        public override iDS IsReady(string namefile)
        {

            iDS temp = null;
            if (namefile == ".port")
            {
                this.fileName = namefile;
                temp = this;
            }
            else if (this.next != null)
            {
                temp = next.IsReady(this.fileName);
            }
            return temp;
        }

        //--------------------------------------------------------
        public override string GetFilter()
        {
            string temp = "TcpClient (*.port)|*.port";
            if (this.next != null)
            {
                temp += "|" + next.GetFilter();
            }
            return temp;
        }

        internal void SendFile(string fileName)
        {
            byte[] file = File.ReadAllBytes(fileName);
            string[] name = fileName.Split('\\');
            //string request = "SENDFILE;" + name[name.Length - 1] + ";";
            try
            {
                string host = System.Net.Dns.GetHostName();
                int port = 8000;
                WebClient client = new WebClient();

                //Send message
                byte[] buf = client.UploadData("http://" + host + ":" + port + "/SENDFILE:" + name[name.Length - 1] + ":", file);
                //decoding from bytes array to string
                string answer = Encoding.ASCII.GetString(buf);
                client.Dispose();
                //analyse answer from Net_Server
                if (answer == "fail")
                {
                    throw new SystemException("DS_Net_Client.Create(Person _newPerson) failed");
                }

                // else
                // Parsing the answer
                if (answer == "success")
                {
                    throw new Exception("success");
                }
            }
            catch (Exception t)
            {
                MessageBox.Show(t.Message, "exeption");
            }
        }
    }
}
